import axios from 'axios';
import moment from 'moment';
//import crypto from 'crypto';
import WXBizMsgCrypt from 'wechat-crypto';

/**服务端十分钟推一次票据 接收到需要先存到本地，以防止重启时无票据 */
let component_verify_ticket = 'ticket@@@bmZRN3t-kFa8m6lVtnZVCGdhvVkD8m317jUtR_iHMfJXo9GVtSoSbLDrLPflqmKCXps2bp-xt8rx1kewpK2-Fg';
/**开放平台的appid */
let component_appid = 'wxe04119009281afb8';
/**开放平台的appsecret */
let component_appsecret = '46320d4ab3bf78869d8a8100d09d74ed';
/**消息校验Token */
const token = '6D670B403188'; // 替换为您的Token
/**消息加解密Key */
const encodingAesKey = '1234567890123456789012345678901234567890123'; // 替换为您的EncodingAESKey

const appId = 'wxe04119009281afb8'; // 替换为您的AppId

/**开放平台的token */
let component_access_token = '';
/**开放平台的token过期时间 */
let token_expires_time = moment();
 
let authorizer_access_token ='';
let authorizer_refresh_token ='';
let authorizer_token_expires_time=moment();



async function startPushTicket(component_appid, component_secret) {
    let url = `https://api.weixin.qq.com/cgi-bin/component/api_start_push_ticket`;
    let data = {
        component_appid,
        component_secret
    }
    try {
        let result = await axios.post(url, data);
        console.log(result.data);

    } catch (error) {
        console.log(error.message);
    }
}
/**
 * 获取开放平台的token
 * @returns 
 */
async function getComponentAccessToken() {
    if (moment().isBefore(token_expires_time)) {
        return component_access_token;
    }

    let url = `https://api.weixin.qq.com/cgi-bin/component/api_component_token`;
    let data = {
        component_appid,
        component_appsecret,
        component_verify_ticket
    }
    try {
        let result = await axios.post(url, data);
        console.log(result.data);
        if (result.data.component_access_token) {
            component_access_token = result.data.component_access_token;
            token_expires_time = moment().add(result.data.expires_in, 'seconds');
        }
        return component_access_token;

    } catch (error) {
        console.log(`getComponentAccessToken error :${error.message}`);
    }
    component_access_token = '';
    token_expires_time = moment();
    return component_access_token;
}
/**
 * 获取预授权码
 * @returns 
 */
async function getPreAuthCode() {

    let access_token = await getComponentAccessToken();
    if (access_token == null) {
        return {
            errcode: -1,
            errmsg: 'getComponentAccessToken error'
        }
    }
    let url = `https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=${component_access_token}`;
    let data = {
        component_appid
    }
    try {
        let result = await axios.post(url, data);
        console.log(result.data);

        if (result.data.pre_auth_code == null) {
            return {
                errcode: -1,
                errmsg: result.data.errmsg
            }
        }

        let auth_link = `https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=${component_appid}&pre_auth_code=${result.data.pre_auth_code}&redirect_uri=http://pa.ktpark.net&auth_type=1`;
        return {
            errcode: 0,
            auth_link: auth_link
        }

    } catch (error) {
        console.log(error.message);
        return {
            errcode: -1,
            errmsg: error.message
        }
    }
}


/**
 * 获取authorizer_refresh_token  
 * @param {*} code 授权时服务器发送的AuthorizationCode
 * @returns 
 */
async  function getApiQueryAuth(code) {
    let access_token = await getComponentAccessToken();
    if (access_token == null) {
        return {
            errcode: -1,
            errmsg: 'getComponentAccessToken error'
        }
    }
    let url = `https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=${component_access_token}`;
    let data = {
        component_access_token,
        component_appid,
        authorization_code: code
    }
    try {
        let result = await axios.post(url, data);
        console.log(result.data);
        if (result.data.authorization_info) {
            authorizer_access_token = result.data.authorization_info.authorizer_access_token;
            authorizer_refresh_token = result.data.authorization_info.authorizer_refresh_token;
            authorizer_token_expires_time = moment().add(result.data.authorization_info.expires_in, 'seconds');
        }
        return authorizer_access_token;
    } catch (error) {
        console.log(error.message);
    }
}

/**
 * 获取代公众号调用接口的token
 * @returns 
 */
async   function getApiToken() {
    await getApiQueryAuth(authCode)
    if(moment().isBefore(authorizer_token_expires_time)){
        return authorizer_access_token;
    }
    let url = `https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=${component_access_token}`;
    let data = {
        component_access_token,
        component_appid,
        authorizer_appid:'wx4cc7809cd7884e63',
        authorizer_refresh_token
    }
    try {
        let result = await axios.post(url, data);
        console.log(result.data);
        if (result.data.authorizer_access_token) {
            authorizer_access_token = result.data.authorizer_access_token;
            authorizer_refresh_token = result.data.authorizer_refresh_token;
            authorizer_token_expires_time = moment().add(result.data.expires_in, 'seconds');
        }
        return authorizer_access_token;
    } catch (error) {
        console.log(error.message);
    }
    authorizer_access_token = '';
    authorizer_refresh_token = '';
    authorizer_token_expires_time = moment();
    return authorizer_access_token;
}

/**
 * 微信开放平台下发的密文消息解密
 * @param {*} encrypt 密文
 */
async function decryptMsg(encrypt) {
    // 初始化 WXBizMsgCrypt 实例
    const crypto = new WXBizMsgCrypt(token, encodingAesKey, component_appid);
    const decryptedMessage = crypto.decrypt(encrypt);
    console.log('解密后的消息:', decryptedMessage);
}


/**
 *  代公众号调用接口发送模板消息
 * @param {*} data 
 * @returns 
 */
async function SendTemplateMessage_obj(data) {
    let access_token = await getApiToken();
    if (access_token == null) {
        return {
            errcode: -1,
            errmsg: 'getComponentAccessToken error'
        }
    }
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`;
    try {
        let res = await axios.post(url, data);
        console.log(res.data);
    } catch (error) {
        console.log(error.message);
    }

}

const   authCode =`queryauthcode@@@Gwm3c2FVa-UonHQc_k6KptV0x0nzl-smaBOspBuiRD4EnH6_EqknBJpCEjQ31S22W6n5hVyZ47GNHZA1vpsz4g`


//加解密的相关的方法


// // 要加密的明文消息
// const plainText = 'Hello, WeChat!';

// // 加密消息
// const encryptedMessage = crypto.encrypt(plainText);s

// console.log('加密后的消息:', encryptedMessage);

// // 解密消息
// const decryptedMessage = crypto.decrypt('659YgI/BYQfaC8gwCTxz4bV2vHeIwzodSNReMcgzkjac9XIjsjoDMWgKlE33XYnXm3RY7gVQ/zs+EsLswFHFxnbVWGH3faBPWwpimEszVxUpy0zvAYmWSCkQpAHflQ8HIFJuiOOv630oJSEjdP7mfRHsH33guXaMN8RZqQRDVu7oHTPl30M5LjXUBN/6bCHwkWi+6sdtlewHkzskahnzmXrWLH5Oz/bETDQswo+i2R3jyFnJKeMnz4zmW07/8I1XAI0qyDNJhYlz3NbLRpX+RsYp51dGEZw8sdfE64Y+gXdPxnrPJ4w2zHoKxJbmLVqoabhBEJHg1NRZeT+Sg693IhvU+FSPn2j49f2A3JYy038K0Ju4xvXA5c9i6JEQCbNGMgaXxdxfBJOvK+soEFN7tGe6QCpyy7ukGkbZ/yhToYZWDJBujfK1mWxU2UMT2UV/vdMKExrLLUZDOe0H7dEmnA==');

// console.log('解密后的消息:', decryptedMessage);

// async function test() {

//     // getComponentAccessToken(component_appid,component_appsecret,component_verify_ticket);
//    // getApiQueryAuth(authCode);

//     let data = {
//         touser:'o3Vgo6GHSGYJbQG7jvdkfbOiOKgM',
//         template_id: "oFeBwPjJAXtfMUdBjpLjZ6IKw-whZ2L-t9Gg__SB2Ko",
//         //带车牌号的预支付地址
//         url: `http://www.baidu.com`,
//         data: {
//             car_number1: { value: '鄂A12345' },
//             thing2: { value: "安快智能" },
//             time3: { value: moment().format('YYYY-MM-DD HH:mm:ss') },
//         }
//     };
//     SendTemplateMessage_obj(data);

//     // let   link=await getPreAuthCode();
//     // console.log("link",link);

//     //https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=wxe04119009281afb8&pre_auth_code=preauthcode@@@ZLIgiuUflkbvug--QbkIQKggFpzHyisxccQy5QWKm-wbRmSV1E8I1LaZlQTwQOUXuruxa-qqXi41hUsfSOv0HA&redirect_uri=http://pa.ktpark.net
//     // decryptMsg('P0aR9hog6rdOzoT29O3G0TVCLBySTLiU2LTy2MQapfCgXjrqTUeD7vakrSIAS0PY/0VzDdMiveia3xDUTl3r5XzrtAZCqb/3d7EI1zbs3sC7PrwLpvE3kazH8lPbQvHjBZujQCHrqtVK715tCyus3R/HF48Plh+6bjuy0Tl6MiEJw1qByLQ9CDVqHL/gx2C3fEnNcmw8cRhyBRN+u7k5AiBXrglUR9TLA2aVDHXVkHOkKe61L+/dtUN7/icCcfW0WBvKU7aPwXnA2rQEJvWk3qQqwsQmwLluvi+LhaHZPRuHxTiOyOH9Bn0JHKCYpaF2k99iktz+wxAcK+5Togd+Wv9JpFM0lFFf3I8svgEYzOsv4kHnUZKyrVF2k3s8r3WSjufu2A3oKryT7KVss8a5ZK7mEVKUhnioOpCjX2Bl1YI8XMsuXZSxRTcY6mc6H7Vg1KWu0jibXlfT5gIxaafDHPOcfqe6055d8xjomoMGxCRiL8MX2486/yq3Ng4b9nD5ECN8qOR0CooqSWaoXQf+xcvo1HGux0dl4wOxZEXnmo5wcSsc8HJ+y1073jPeRBZsS7QmJ6xovjSBCaqGIgB/p37YIY49++DuNGmftvwkKlAWObii7tcg4YSnJ1mxKFjxltAst+T5qC8fqDB7hfcJzPdyDNJ/NXrLNCP9OwC2NAarrm8nBzW1M5Pie2C//zsSO1wFqDCtYNu/Kyz9Yjz3mfra+6vQ1K+l3cLhfb0AZ5gBEh281gtW88XWQUEEA4LVjXePSf9070+cPqyVUjFxy26co83hR7MF/2MX8MLflA3O24x3iqdEhbFv+ThdEAZRiWjhelNdFuPHnZCK8CBSkA==')
// }
 export default {decryptMsg};


